class_name TrailPathFindingRecorder
extends Node2D

class Record:
	var tick:float
	var position:Vector2
	func _init(t,p) -> void:
		self.tick = t
		self.position = p
#region 属性
## 记录者，主要用来获得Position，如果不设置，将会用该节点的Position代替
@export var recorder:Node2D
@export var record_interval:float = 0.1
@export var record_max_amount:int = 100
## 执行记录的最小距离，如果小于这个距离认为没有移动，不会记录
@export var record_mix_distance:float = 0.1
## 记录的有效时间，如果超过这个时间会被移除，负数表示永久有效
@export var record_left_time:float = -1
@export var debug:bool = false
@export var debug_circle_radius:float = 5
var record_timer:Timer
var records:Array[Record] = []
var connect_obj:ConnectObj
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
#endregion
#region 公共方法
func get_recorder_position() -> Vector2:
	return recorder.global_position if recorder else global_position
func get_records() -> Array[Record]:
	_update_records()
	return records
#endregion
#region 私有方法
func _check_record_left_time(record:Record) -> bool:
	if record_left_time < 0:
		return true
	return Time.get_ticks_msec() <= record.tick + record_left_time * 1000
func _update_records():
	records = records.filter(_check_record_left_time)
	while records.size() > record_max_amount:
		records.pop_front()
func _record():
	if records.size() > 0:
		var last_record = records[-1]
		if (last_record.postion - get_recorder_position()).length() < record_mix_distance:
			return
	records.append(Record.new(Time.get_ticks_msec(),get_recorder_position()))
	_update_records()
#endregion
#region 生命周期函数
func _ready() -> void:
	record_timer = Timer.new()
	record_timer.wait_time = record_interval
	record_timer.autostart = true
	record_timer.one_shot = false
	connect_obj = ConnectObj.new(record_timer.timeout,[_record])
func _notification(what: int) -> void:
	if what == NOTIFICATION_PREDELETE:
		if connect_obj:
			connect_obj.disconnect_all()
func _draw() -> void:
	if debug and records:
		for record in records:
			var color = Color.GREEN
			color.a = 1 - (Time.get_ticks_msec() - record.tick)/1000/(10 if record_left_time < 0 else record_left_time)
			draw_circle(record.position,debug_circle_radius,color,true)
#endregion
